package com.mrzhou.gateway.dynamic;

import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 基于nacos的动态路由配置
 * @author qiang.zhou
 * @deprecated 目前不在采用此方式设值 现使用com.mrzhou.gateway.filter.RequestFilter设置路由配置
 */
@Service
@Deprecated
public class DynamicRouteService implements ApplicationEventPublisherAware {

    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher publisher;

    public DynamicRouteService(RouteDefinitionWriter routeDefinitionWriter) {
        this.routeDefinitionWriter = routeDefinitionWriter;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    /**
     * 增加路由
     */
    public String save(RouteDefinition definition) {
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success save route";
        } catch (Exception e) {
            return "fail save route";
        }
    }

    /**
     * 更新路由
     */
    public String update(RouteDefinition definition) {
        try{
            routeDefinitionWriter.delete(Mono.just(definition.getId()));
        } catch (Exception e) {
            return "update fail,not find route  routeId: "+definition.getId();
        }
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success update route";
        } catch (Exception e) {
            return "fail update route";
        }
    }

    /**
     * 批量更新路由
     */
    public String updateList(List<RouteDefinition> definition) {
        definition.forEach(this::update);
        return "update success route";
    }

    /**
     * 删除路由
     */
        public String delete(RouteDefinition definition) {
            try{
                routeDefinitionWriter.delete(Mono.just(definition.getId()));
                return "delete success route";
            } catch (Exception e) {
                return "delete fail,not find route  routeId: "+definition.getId();
            }
    }

}
